<template>
  <div class="app-container">
    <el-date-picker
      v-model="value2"
      type="datetimerange"
      :picker-options="pickerOptions"
      value-format="yyyy-MM-dd HH:mm:ss"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      align="right"
      :default-time="['12:00:00', '08:00:00']"
      @change="endDate"
    >
    </el-date-picker>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:award:add']"
          >查看全部</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:award:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="awardList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="index" width="50"> </el-table-column>
      <el-table-column label="ID" align="center" prop="userId" />
      <el-table-column label="用户" align="center" prop="username" width="200">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center">
            <el-avatar :src="scope.row.headimg"></el-avatar>
            <div>{{ scope.row.username }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="流水" align="center" prop="sum" />

      <!-- <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:award:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:award:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  listAward,
  getAward,
  delAward,
  addAward,
  updateAward,
  listConsume,
} from "@/api/top/top_jiang.js";
import { getMy_user } from "@/api/users/user.js";

export default {
  name: "Award",
  dicts: ["award_type", "top_type"],

  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value2: ["2022-06-21 00:14:37", "2022-06-21 00:14:37"],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 排行榜奖励类型表格数据
      awardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        leaderboardTypeId: null,
        type: null,
        award: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        leaderboardTypeId: [
          { required: true, message: "排行榜id不能为空", trigger: "blur" },
        ],
        type: [
          {
            required: true,
            message:
              "奖励类型 1 - 5 对应 第一名 第二名 第三名 前50 前100不能为空",
            trigger: "change",
          },
        ],
        award: [
          { required: true, message: "积分奖励不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.gettime();
    this.getList(this.value2);
  },
  methods: {
    //查询用户信息
    async queryUser(arr) {
      let val = arr;
      for (let index = 0; index < arr.length; index++) {
        console.log(arr[index].userId);
        await getMy_user(arr[index].userId).then((response) => {
          if (response.data) {
            this.$set(
              this.awardList[index],
              "username",
              response.data.nickname
            );
            this.$set(this.awardList[index], "headimg", response.data.headimg);
          }
        });
      }
    },
    /** 查询排行榜奖励类型列表 */
    getList(data) {
      this.loading = true;
      listConsume({
        end: this.value2[1],
        start: this.value2[0],
      }).then((response) => {
        this.awardList = response.data;
        this.queryUser(this.awardList);
        // this.total = response.total;
        this.loading = false;
      });
    },
    //获取当天时间段
    gettime(val) {
      //获取前一天及今天的数据
      let ts_begin = new Date();
      let ts_end = new Date();
      ts_begin.setTime(
        ts_begin.getTime() -
          3600 * 1000 * ts_begin.getHours() -
          60 * 1000 * ts_begin.getMinutes() -
          1000 * ts_begin.getSeconds()
      );
      ts_end.setTime(ts_begin.getTime() + 3600 * 1000 * 24 - 1000);
      //格式化Sat Jul 23 2022 00:00:00 GMT+0800 (中国标准时间)

      this.value2 = [
        this.msToDate(ts_begin).hasTime,
        this.msToDate(ts_end).hasTime,
      ];
      console.log(this.value2);
    },
    msToDate(msec) {
      let datetime = new Date(msec);
      let year = datetime.getFullYear();
      let month = datetime.getMonth();
      let date = datetime.getDate();
      let hour = datetime.getHours();
      let minute = datetime.getMinutes();
      let second = datetime.getSeconds();

      let result1 =
        year +
        "-" +
        (month + 1 >= 10 ? month + 1 : "0" + (month + 1)) +
        "-" +
        (date + 1 < 10 ? "0" + date : date) +
        " " +
        (hour + 1 < 10 ? "0" + hour : hour) +
        ":" +
        (minute + 1 < 10 ? "0" + minute : minute) +
        ":" +
        (second + 1 < 10 ? "0" + second : second);

      let result2 =
        year +
        "-" +
        (month + 1 >= 10 ? month + 1 : "0" + (month + 1)) +
        "-" +
        (date + 1 < 10 ? "0" + date : date);

      let result = {
        hasTime: result1,
        withoutTime: result2,
      };

      return result;
    },

    endDate(e) {
      console.log(this.value2);
      this.getList(this.value2);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        leaderboardTypeId: null,
        type: null,
        award: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.value2 = [];
      this.getList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAward(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改排行榜奖励类型";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateAward(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAward(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除排行榜奖励类型编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAward(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/award/export",
        {
          ...this.queryParams,
        },
        `award_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
